/**
 * @description 去单点服务器登录
 */
export const toLogin = () => {
  window.location.href = ssoUrl()
}

/**
 * @description 去单点服务器登出
 */
export const toLogout = token => {
  window.location.href = ssoUrl() + '&session_id=' + token
}
/**
 * @description 去单点服务器地址
 */
export const ssoUrl = url => {
  let pageUrl = window.location.pathname + window.location.search;
  if (pageUrl.indexOf('codeCallback') != -1) {
    pageUrl = process.env.VUE_APP_PORTAL_HOST_URL
  } else {
    pageUrl = encodeURIComponent(pageUrl)
  }
  const portalUrl = process.env.VUE_APP_PORTAL_HOST_URL || pageUrl;
  const ssoHostUrl = process.env.VUE_APP_SSO_HOST_URL;
  const callbackUrl = process.env.VUE_APP_SSO_CALLBACK_URL || 'codeCallback';
  const responseType = process.env.VUE_APP_SSO_RESPONSE_TYPE || 'code';
  const clientId = process.env.VUE_APP_SSO_CLIENT_ID || 'chaos-test';

  let codeCallbackUrl = encodeURIComponent(`${portalUrl}${callbackUrl}?redirect_uri=${pageUrl}`);
  let ssoUrl =
    `${ssoHostUrl}oauth/authorize?response_type=${responseType}&client_id=${clientId}&redirect_uri=${codeCallbackUrl}`
  return ssoUrl
}

export const setToken = token => {
  window.localStorage.setItem(process.env.VUE_APP_SSO_SESSION_TOKEN_KEY || 'sso-token', token)
}

export const getToken = () => {
  const token = window.localStorage.getItem(process.env.VUE_APP_SSO_SESSION_TOKEN_KEY || 'sso-token')
  if (token) {
    return token
  }
  return false
}

export const removeToken = () => {
  window.localStorage.removeItem(process.env.VUE_APP_SSO_SESSION_TOKEN_KEY || 'sso-token')
}

export const setUser = user => {
  window.localStorage.setItem(process.env.VUE_APP_SSO_SESSION_USER_KEY || 'sso-user', JSON.stringify(user))
}

export const getUser = () => {
  const user = window.localStorage.getItem(process.env.VUE_APP_SSO_SESSION_USER_KEY || 'sso-user')
  if (user) return JSON.parse(user)
  else return false
}

export const removeUser = () => {
  window.localStorage.removeItem(process.env.VUE_APP_SSO_SESSION_USER_KEY || 'sso-user')
}